﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using Novacode;
using Unis.Framework.Core.Infrastructure;
using Unis.Framework.Core.Utility;

using NPOI.SS.Util;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using BorderStyle = NPOI.SS.UserModel.BorderStyle;
using VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment;
using DotNet.Service;
using KingRoad.EPM.ProjectInfoBLL;
using KingRoad.EPM.CompletionMaterialsEntity.Model;
using KingRoad.EPM.CompletionMaterialsBLL.UIRules;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;


namespace KingRoad.EPM.Web.Areas.CompletionMaterials.Controllers
{
    public class BaseController : Controller
    {
        public const int ALL_RECORD_ITEMS = 1000000;
        public const int CURRENT_PAGE_NUM = 0;
        /// <summary>
        /// 施工单位标段UIRule
        /// </summary>
        public ProjectSegmentUIRule ProjectSegmentUIRule
        {
            get { return EngineContext.Current.Resolve<ProjectSegmentUIRule>(); }
        }
        /// <summary>
        /// 数据字典客户端UIRule
        /// </summary>
        public ScmSafetyconstructiondicUIRule ScmSafetyconstructiondicUIRule
        {
            get { return EngineContext.Current.Resolve<ScmSafetyconstructiondicUIRule>(); }
        }
        /// <summary>
        /// 归档材料类型表管理UIRule
        /// </summary>
        public BcdFiledataUIRule BcdFiledataUIRule
        {
            get { return EngineContext.Current.Resolve<BcdFiledataUIRule>(); }
        }
        /// <summary>
        /// 工程项目表
        /// </summary>
        public BcdProjectUIRule BcdProjectUIRule
        {
            get { return EngineContext.Current.Resolve<BcdProjectUIRule>(); }
        }
        /// <summary>
        /// 工程项目与材料类型关系表
        /// </summary>
        public BcdProjectfileUIRule BcdProjectfileUIRule
        {
            get { return EngineContext.Current.Resolve<BcdProjectfileUIRule>(); }
        }
        /// <summary>
        /// 工程项目与材料类型关系表（临时表在修改时用，平时数据为空）
        /// </summary>
        public BcdProjectfiletempUIRule BcdProjectfiletempUIRule
        {
            get { return EngineContext.Current.Resolve<BcdProjectfiletempUIRule>(); }
        }
        /// <summary>
        /// 归档类型表与案卷目录对应关系表
        /// </summary>
        public BcdFiledatalistUIRule BcdFiledatalistUIRule
        {
            get { return EngineContext.Current.Resolve<BcdFiledatalistUIRule>(); }
        }
        /// <summary>
        /// 案卷目录表
        /// </summary>
        public BcdFilelistUIRule BcdFilelistUIRule
        {
            get { return EngineContext.Current.Resolve<BcdFilelistUIRule>(); }
        }
        /// <summary>
        /// 卷内目录表
        /// </summary>
        public BcdVolumedirectoryUIRule BcdVolumedirectoryUIRule
        {
            get { return EngineContext.Current.Resolve<BcdVolumedirectoryUIRule>(); }
        }
        /// <summary>
        /// 文件材料
        /// </summary>
        public ScmAttachsfilesUIRule ScmAttachsfilesUIRule
        {
            get { return EngineContext.Current.Resolve<ScmAttachsfilesUIRule>(); }
        }
        /// <summary>
        /// 工程项目竣工资料材料类型表
        /// </summary>
        public BcdProfiletypeUIRule BcdProfiletypeUIRule
        {
            get { return EngineContext.Current.Resolve<BcdProfiletypeUIRule>(); }
        }
        /// <summary>
        /// 当前登录人的ID
        /// </summary>
        public int GetLoginUserId
        {
            get { return Convert.ToInt32(UserService.CurrUserInfo.Id); }
        }
        /// <summary>
        /// 当前登录人的真实姓名
        /// </summary>
        public string GetLoginUserRealName
        {
            get { return UserService.CurrUserInfo.RealName; }
        }
        /// <summary>
        /// 当前登录人的用户名称
        /// </summary>
        public string GetLoginUserName
        {
            get { return UserService.CurrUserInfo.UserName; }
        }
        /// <summary>
        /// 当前登录人的部门编码
        /// </summary>
        public string GetLoginUserDepartmentCode
        {
            get { return UserService.CurrUserInfo.DepartmentCode; }
        }
        /// <summary>
        /// 当前登录人的部门ID
        /// </summary>
        public int GetLoginUserDepartmentId
        {
            get { return UserService.CurrUserInfo.DepartmentId.Value; }
        }
        /// <summary>
        /// 当前登录人的部门名称
        /// </summary>
        public string GetLoginUserDepartmentName
        {
            get { return UserService.CurrUserInfo.DepartmentFullName; }
        }
        /// <summary>
        /// 当前登录人所有基础信息实体
        /// </summary>
        public DotNet.Utilities.BaseUserInfo GetLoginUserInfo
        {
            get { return UserService.CurrUserInfo; }
        }
        /// <summary>
        /// 当前项目ID
        /// </summary>
        public int PID
        {
            get
            {
                int ProId = 0;
                ProId = (string.IsNullOrWhiteSpace(UserService.CurrUserInfo.Themes) ? 0 : int.Parse(UserService.CurrUserInfo.Themes));
                return ProId;
            }
        }
        /// <summary>
        /// 当前项目ID
        /// </summary>
        public int PRJID
        {
            get
            {
                int ProId = 0;
                ProId = (string.IsNullOrWhiteSpace(UserService.CurrUserInfo.Themes) ? 0 : int.Parse(UserService.CurrUserInfo.Themes));
                return ProId;
            }
        }
        /// <summary>
        /// 当前项目名
        /// </summary>
        public string PRJName
        {
            get
            {
                string name = "";
                if (PRJID != 0)
                {
                    var info = new KingRoad.EPM.ProjectInfoBLL.Project_PrjInfoBLL().GetEntityById(PRJID);
                    if (info != null)
                        name = info.PRJINFO_NAME;
                }
                return name;
            }
        }
        /// <summary>
        /// 当前项目业主单位
        /// </summary>
        public string PRJUName
        {
            get
            {
                string name = "";
                if (PRJID != 0)
                {
                    var info = new KingRoad.EPM.ProjectInfoBLL.Project_PrjInfoBLL().GetEntityById(PRJID);
                    if (info != null)
                        name = info.PRJINFO_OWNER;
                }
                return name;
            }
        }
        /// <summary>
        /// 当前项目编号
        /// </summary>
        public string PRJCode
        {
            get
            {
                string name = "";
                if (PRJID != 0)
                {
                    var info = new KingRoad.EPM.ProjectInfoBLL.Project_PrjInfoBLL().GetEntityById(PRJID);
                    if (info != null)
                        name = info.PRJINFO_CODE;
                }
                return name;
            }
        }

        /// <summary>
        /// 获取标段ID和标段名称
        /// </summary>
        /// <returns></returns>
        public List<KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT> GetSeglist
        {
            get { return new KingRoad.EPM.ProjectInfoBLL.Project_SegmentBLL().GetNowadayOrglist(); }
        }

        /// <summary>
        /// 获取监理的信息列表
        /// </summary>
        public List<DotNet.Model.MyEntity.Base_Organize> GetOrganizeForJL
        {
            get { return new OrganizeService().GetOrganizeByCode("JL").ToList(); }
        }
        /// <summary>
        /// 获取驻地监理的信息列表
        /// </summary>
        public List<DotNet.Model.MyEntity.Base_Organize> GetOrganizeForZDJL
        {
            get { return new OrganizeService().GetOrganizeByCode("ZDJL").ToList(); }
        }
        /// <summary>
        /// 获取检测单位的信息列表
        /// </summary>
        public List<DotNet.Model.MyEntity.Base_Organize> GetOrganizeForJC
        {
            get { return new OrganizeService().GetOrganizeByCode("JC").ToList(); }
        }
        /// <summary>
        /// 当前登录人所属的组织结构
        /// </summary>
        public DotNet.Model.MyEntity.Base_Organize GetLoginUserOrganizeEntity
        {
            get
            {
                return new OrganizeService().GetOrganizeEntityById(GetLoginUserDepartmentId.ToString());
            }
        }


        /// <summary>
        /// 获取当前登录单位所负责监理,检测,驻地监理的综合信息-名称和标段ID
        /// </summary>
        public List<KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT> Get_JL_JC_ZDJL_SegmentInfo
        {
            get
            {
                var list1 = GetJLProjectSegmentInfo;
                var list2 = GetJCProjectSegmentInfo;
                var list3 = GetZDJLProjectSegmentInfo;
                var list = list1.Concat(list2).Concat(list3).ToList();
                return list;
            }
        }
        /// <summary>
        /// 获取当前登录单位所负责监理-名称和标段ID
        /// </summary>
        public List<KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT> GetJLProjectSegmentInfo
        {
            get
            {
                return new KingRoad.EPM.ProjectInfoBLL.Project_SegmentBLL().GetNowadayOrglist(1);
            }
        }
        /// <summary>
        /// 获取当前登录单位所负责检测-名称和标段ID
        /// </summary>
        public List<KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT> GetJCProjectSegmentInfo
        {
            get
            {
                return new KingRoad.EPM.ProjectInfoBLL.Project_SegmentBLL().GetNowadayOrglist(3);
            }
        }
        /// <summary>
        /// 获取当前登录单位所负责驻地监理-名称和标段ID
        /// </summary>
        public List<KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT> GetZDJLProjectSegmentInfo
        {
            get
            {
                return new KingRoad.EPM.ProjectInfoBLL.Project_SegmentBLL().GetNowadayOrglist(4);
            }
        }
        /// <summary>
        /// 获取当前登录单位所负责施工单位信息
        /// </summary>
        public List<KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT> ShiGong_Segment
        {
            get
            {
                return new Project_HTDWFRelagionBLL().GetlistByUserInfo(1);
            }
        }
        /// <summary>
        /// 获取当前登录单位所负责监理,检测,驻地监理 + 施工单位 的综合信息-名称和标段ID
        /// </summary>
        public List<KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT> Get_JL_JC_ZDJL_SG_SegmentInfo
        {
            get
            {
                var list1 = GetJLProjectSegmentInfo;
                var list2 = GetJCProjectSegmentInfo;
                var list3 = GetZDJLProjectSegmentInfo;
                var list4 = ShiGong_Segment;
                var list = list1.Concat(list2).Concat(list3).Concat(list4).ToList();
                return list;
            }
        }
        /// <summary>
        /// 获取当前登录人所管辖的所有标段合同号集合
        /// </summary>
        /// <returns></returns>
        public string Get_JL_JC_ZDJL_SG_SegmentCodes()
        {
            string codes = "";
            foreach (KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT info in Get_JL_JC_ZDJL_SG_SegmentInfo)
            {
                codes += "'" + info.SEGMENT_CODE + "',";
            }
            return codes.Trim(',');
        }

        /// <summary>
        /// 根据标段获取单位信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ProjectUnitInfo GetUnitInfoByCode(string code)
        {
            ProjectUnitInfo info = new ProjectUnitInfo();
            List<KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT> list = Get_JL_JC_ZDJL_SG_SegmentInfo.Where(p => p.SEGMENT_CODE == code).ToList();
            if (list.Count > 0)
            {
                info.UNIT_CODE = list[0].SEGMENT_CODE;
                info.UNIT_NAME = list[0].SEGMENT_DEPARTNAME;
                info.UNIT_ID = list[0].SEGMENT_ORGID == null ? 0 : Convert.ToInt32(list[0].SEGMENT_ORGID);
            }
            return info;
        }
        /// <summary>
        /// 根据类型获取标段信息
        /// </summary>
        /// <param name="type">0=监理单位 1=施工单位 2=所有单位</param>
        /// <returns></returns>
        public List<ProjectUnitInfo> GetUnitListByType(int type)
        {
            List<ProjectUnitInfo> list = new List<ProjectUnitInfo>();
            List<KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT> tlist = new List<ProjectInfoEntity.PROJECT_SEGMENT>();
            if (type == 0)
            {
                tlist = Get_JL_JC_ZDJL_SegmentInfo;
            }
            if (type == 1)
            {
                tlist = ShiGong_Segment;
            }
            if (type == 2)
            {
                tlist = Get_JL_JC_ZDJL_SG_SegmentInfo;
            }
            foreach (KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT tinfo in tlist)
            {
                ProjectUnitInfo info = new ProjectUnitInfo();
                info.UNIT_CODE = tinfo.SEGMENT_CODE;
                info.UNIT_NAME = tinfo.SEGMENT_DEPARTNAME;
                info.UNIT_ID = tinfo.SEGMENT_ORGID == null ? 0 : Convert.ToInt32(tinfo.SEGMENT_ORGID);
                list.Add(info);
            }
            return list;
        }
        public List<KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT> JianLi_Segment
        {
            get
            {
                return new Project_HTDWFRelagionBLL().GetlistByUserInfo(2);
            }
        }

        public List<KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT> JianCe_Segment
        {
            get
            {
                return new Project_HTDWFRelagionBLL().GetlistByUserInfo(4);
            }
        }

        public List<KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT> ZhuDiJianLi_Segment
        {
            get
            {
                return new Project_HTDWFRelagionBLL().GetlistByUserInfo(5);
            }
        }

        /// <summary>
        /// 根据URL获取模块ID
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public int GetEntityByUrl(string url)
        {
            return new ModuleService().GetEntityByUrl(url).Id;
        }

        #region Methods

        /// <summary>
        /// 获取RequestForm的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T GetRequestFormValue<T>(string key) where T : IConvertible
        {
            if (Request.Form[key] == null) return default(T);
            //{
            //if (typeof(T).Name == "Int32") 
            //}

            return (T)Convert.ChangeType(Request.Form[key], typeof(T));
        }
        /// <summary>
        /// 根据文件路径获取xml的XDocumen对象
        /// </summary>
        /// <param name="xmlpath">xml服务器端路径</param>
        /// <returns></returns>
        public XDocument LinqLoadXmlFromPath(string xmlpath)
        {

            if (String.IsNullOrEmpty(xmlpath))
                throw new NullReferenceException("xml路径为空!");
            if (!System.IO.File.Exists(xmlpath))
                throw new NullReferenceException("该目录下不存在该文件!");
            return XDocument.Load(xmlpath);
        }

        /// <summary>
        /// 设置excel样式
        /// </summary>
        /// <param name="book">工作簿</param>
        /// <param name="align">水平对齐方式（center、left、right）</param>
        /// <param name="border">是否有边框</param>
        /// <param name="size">字体大小</param>
        /// <param name="weight">字体粗细</param>
        /// <returns></returns>
        public ICellStyle Getcellstyle(IWorkbook book, string align = "center", bool border = true, short size = 10, short weight = 100)
        {
            ICellStyle style = book.CreateCellStyle();
            //垂直对齐
            style.VerticalAlignment = VerticalAlignment.Center;
            //自动换行
            style.WrapText = true;
            //水平对齐
            switch (align)
            {
                case "center":
                    style.Alignment = HorizontalAlignment.Center;
                    break;
                case "left":
                    style.Alignment = HorizontalAlignment.Left;
                    break;
                case "right":
                    style.Alignment = HorizontalAlignment.Right;
                    break;
                default:
                    style.Alignment = HorizontalAlignment.Center;
                    break;
            }
            //字体
            IFont font = book.CreateFont();
            font.FontHeightInPoints = size;
            font.Boldweight = weight;
            style.SetFont(font);
            if (border)
            {
                style.BorderTop = BorderStyle.Thin;
                style.BorderBottom = BorderStyle.Thin;
                style.BorderLeft = BorderStyle.Thin;
                style.BorderRight = BorderStyle.Thin;
            }
            return style;
        }
        /// <summary>
        /// 创建单元格
        /// </summary>
        /// <param name="row">行实体</param>
        /// <param name="index">列数</param>
        /// <param name="style">单元格样式</param>
        /// <param name="value">单元格值</param>
        public void CreateCell(IRow row, int column, ICellStyle style, string value)
        {
            ICell cell = row.CreateCell(column);
            cell.CellStyle = style;
            cell.SetCellValue(value);
        }
        /// <summary>
        /// 根据Excel列类型获取列的值
        /// </summary>
        /// <param name="cell">单元格</param>
        /// <returns></returns>
        public string GetCellValue(ICell cell)
        {
            if (cell == null)
                return string.Empty;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return string.Empty;
                case CellType.Boolean:
                    return cell.BooleanCellValue.ToString();
                case CellType.Error:
                    return cell.ErrorCellValue.ToString();
                case CellType.Numeric:
                    if (DateUtil.IsCellDateFormatted(cell))
                    {
                        return cell.DateCellValue.ToString();
                    }
                    else
                    {
                        return cell.ToString();
                    }
                case CellType.Unknown:
                default:
                    return cell.ToString();
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Formula:
                    try
                    {
                        HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                        e.EvaluateInCell(cell);
                        return cell.ToString();
                    }
                    catch
                    {
                        return cell.NumericCellValue.ToString();
                    }
            }
        }
        #endregion
        /// <summary>
        /// 获取和案卷脊背中的文件类型信息
        /// </summary>
        /// <param name="pIds"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetFileParTypeName(string pIds, string name)
        {
            if (pIds != null)
            {
                string pPId = pIds.Split(',')[1].Trim('\'');
                BcdProfiletypeInfo pPInfo = BcdProfiletypeUIRule.GetEntityById(new Guid(pPId));
                name = pPInfo.Fd_Name;
            }
            if (name == "工程交竣工验收")
                name = "工程交竣工";
            else
                name = name.Substring(0, 4);
            return name;
        }

        /// <summary>
        /// 导出案卷目录
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public void ExportToWord(string fileName, List<BcdFilelistInfo> list)
        {
            string path = Server.MapPath("~/Areas/CompletionMaterials/Upload/" + fileName);
            string savePath = Server.MapPath("~/Areas/CompletionMaterials/Upload/Temp/" + DateTime.Now.Ticks.ToString() + fileName);
            using (DocX docx = DocX.Load(path))
            {
                Regex reg = new Regex(@"\D+");
                docx.Bookmarks.ForEach(f =>
                {
                    string bookMarkName = f.Name;
                    int i = 0;
                    string index = reg.Replace(bookMarkName, "");
                    if (index != "")
                    {
                        bookMarkName = f.Name.Replace(index, "");
                        i = Convert.ToInt32(index);
                    }
                    if (index != "")
                    {
                        if (i < list.Count)
                        {
                            BcdFilelistInfo info = list[i];
                            if (info.ContainProperty(bookMarkName))
                            {
                                var obj = Reflection.GetProperty(info, bookMarkName);
                                var value = obj ?? "";
                                var propertyType = value.GetType().FullName;
                                if (propertyType == "System.DateTime")
                                {
                                    if (bookMarkName == "Fl_StartDate" || bookMarkName == "Fl_EndDate")
                                    {
                                        var endObj = Reflection.GetProperty(info, "Fl_EndDate");
                                        var endVal = endObj ?? "";
                                        if (endVal != "")
                                            endVal = Convert.ToDateTime(endVal).ToString("yyyy.MM");
                                        if (value != "" && endVal != "")
                                            endVal = "-" + endVal;
                                        f.SetText(Convert.ToDateTime(value).ToString("yyyy.MM") + endVal);
                                    }
                                    else
                                        f.SetText(Convert.ToDateTime(value).ToString("yyyy年MM月dd日"));
                                }
                                else
                                    f.SetText(value.ToString());
                            }
                        }
                    }
                });
                if (list.Count > 15)
                {
                    for (int i = 1; list.Count > 15; i++)
                    {
                        list = list.Skip(15).ToList();
                        docx.InsertDocument(GetSonExportInfo("案卷目录1.docx", list), true);
                    }
                }
                docx.SaveAs(savePath);
            }
            DownloadFile(Server.UrlEncode(fileName), savePath, true);//下载文件
        }
        /// <summary>
        /// 案卷目录下一页
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public DocX GetSonExportInfo(string fileName, List<BcdFilelistInfo> list)
        {
            string path = Server.MapPath("~/Areas/CompletionMaterials/Upload/" + fileName);
            using (DocX docx = DocX.Load(path))
            {
                Regex reg = new Regex(@"\D+");
                docx.Bookmarks.ForEach(f =>
                {
                    string bookMarkName = f.Name;
                    int i = 0;
                    string index = reg.Replace(bookMarkName, "");
                    if (index != "")
                    {
                        bookMarkName = f.Name.Replace(index, "");
                        i = Convert.ToInt32(index);
                    }
                    if (index != "")
                    {
                        if (i < list.Count)
                        {
                            BcdFilelistInfo info = list[i];
                            if (info.ContainProperty(bookMarkName))
                            {
                                var obj = Reflection.GetProperty(info, bookMarkName);
                                var value = obj ?? "";
                                var propertyType = value.GetType().FullName;
                                if (propertyType == "System.DateTime")
                                {
                                    if (bookMarkName == "Fl_StartDate" || bookMarkName == "Fl_EndDate")
                                    {
                                        var endObj = Reflection.GetProperty(info, "Fl_EndDate");
                                        var endVal = endObj ?? "";
                                        if (endVal != "")
                                            endVal = Convert.ToDateTime(endVal).ToString("yyyy.MM");
                                        if (value != "" && endVal != "")
                                            endVal = "-" + endVal;
                                        f.SetText(Convert.ToDateTime(value).ToString("yyyy.MM") + endVal);
                                    }
                                    else
                                        f.SetText(Convert.ToDateTime(value).ToString("yyyy年MM月dd日"));
                                }
                                else
                                    f.SetText(value.ToString());
                            }
                        }
                    }
                });
                return docx.Copy();
            }
        }
        /// <summary>
        /// 导出案卷
        /// </summary>
        public void ExportFileToWord(BcdFilelistInfo info, List<BcdVolumedirectoryInfo> list, bool isDownload = true)
        {
            string path = Server.MapPath("~/Areas/CompletionMaterials/Upload/案卷.docx");//模板路径
            string fileName = "案卷" + info.Fl_Code.Replace("/", "_") + "-" + info.Fl_Numb.ToString("D3");//案卷名
            string savePath = Server.MapPath("~/Areas/CompletionMaterials/Upload/Temp/" + info.Fl_Item + "/" + info.Fl_FileType + "/案卷");//文件夹路径
            if (System.IO.Directory.Exists(savePath) == false)//判断文件夹是否存在
                System.IO.Directory.CreateDirectory(savePath);//创建文件夹
            savePath = Server.MapPath("~/Areas/CompletionMaterials/Upload/Temp/" + info.Fl_Item + "/" + info.Fl_FileType + "/案卷/" + fileName + ".docx");//案卷路径
            using (DocX docx = DocX.Load(path))
            {
                Regex reg = new Regex(@"\D+");
                docx.Bookmarks.ForEach(f =>
                {
                    string bookMarkName = f.Name;
                    int i = 0;
                    string index = reg.Replace(bookMarkName, "");
                    if (index != "")
                    {
                        bookMarkName = f.Name.Replace(index, "");
                        i = Convert.ToInt32(index);
                    }
                    if (info.ContainProperty(bookMarkName))
                    {
                        var obj = Reflection.GetProperty(info, bookMarkName);
                        var value = obj ?? "";
                        var propertyType = value.GetType().FullName;
                        if (propertyType == "System.DateTime")
                        {
                            f.SetText(Convert.ToDateTime(value).ToString("yyyy年MM月dd日"));
                        }
                        else
                            f.SetText(value.ToString());

                        if (bookMarkName == "Fl_StartDate")
                        {
                            string valueDate = "";

                            if (value.ToString() != "")
                                value = Convert.ToDateTime(value).ToString("yyyy.MM");
                            var endObj = Reflection.GetProperty(info, "Fl_EndDate");
                            var endVal = endObj ?? "";
                            if (endVal.ToString() != "")
                                endVal = Convert.ToDateTime(endVal).ToString("yyyy.MM");

                            if (value.ToString() != "" && endVal.ToString() != "")
                                valueDate = value.ToString() + "-" + endVal.ToString();
                            else
                                valueDate = value.ToString() + endVal.ToString();

                            f.SetText(valueDate);
                        }
                        if (bookMarkName == "Fl_Numb")
                        {
                            f.SetText(Convert.ToInt32(value).ToString("D3"));
                        }
                    }
                    if (index != "")
                    {
                        if (i < list.Count)
                        {
                            BcdVolumedirectoryInfo vInfo = list[i];
                            if (vInfo.ContainProperty(bookMarkName))
                            {
                                var obj = Reflection.GetProperty(vInfo, bookMarkName);
                                var value = obj ?? "";
                                var propertyType = value.GetType().FullName;
                                if (propertyType == "System.DateTime")
                                    f.SetText(Convert.ToDateTime(value).ToString("yyyy.MM.dd"));
                                else
                                    f.SetText(value.ToString());
                            }
                        }
                    }
                });
                docx.SaveAs(savePath);
            }

            List<string> listFJ = new List<string>();//文件真实路径
            List<string> listFJName = new List<string>();//文件名称
            //添加案卷
            listFJ.Add(savePath);
            listFJName.Add(fileName + ".docx");
            //添加案卷脊背
            listFJ.Add(ExportFileBack(info, fileName));
            listFJName.Add(fileName + "脊背.docx");
            //遍历案卷中的卷内文件（即附件）
            foreach (BcdVolumedirectoryInfo vinfo in list)
            {
                string vpath = Server.MapPath(String.Format("~/Files/{0}", FilePath(vinfo.Vd_ID, vinfo.Pft_ID)));
                DirectoryInfo di = new DirectoryInfo(vpath);
                //找到该目录下的文件 
                FileInfo[] fis = di.GetFiles();
                //遍历卷内文件附件
                foreach (FileInfo fi in fis)
                {
                    listFJ.Add(fi.FullName);
                    listFJName.Add(fi.Name);
                }
            }
            ZipFileMain(listFJ.ToArray(), listFJName.ToArray(), Server.MapPath("~/Areas/CompletionMaterials/Upload/Temp/" + info.Fl_Item + "/" + info.Fl_FileType + "/" + fileName + ".zip"));//压缩文件
            if (isDownload)
                DownloadFile(Server.UrlEncode(fileName + ".zip"), Server.MapPath("~/Areas/CompletionMaterials/Upload/Temp/" + info.Fl_Item + "/" + info.Fl_FileType + "/" + fileName + ".zip"));//下载文件
        }
        /// <summary>
        /// 导出案卷脊背
        /// </summary>
        /// <param name="info">案卷信息</param>
        /// <returns></returns>
        private string ExportFileBack(BcdFilelistInfo info, string fileName)
        {
            string path = Server.MapPath("~/Areas/CompletionMaterials/Upload/案卷脊背.docx");//模板路径
            string savePath = Server.MapPath("~/Areas/CompletionMaterials/Upload/Temp/" + info.Fl_Item + "/" + info.Fl_FileType + "/脊背");//文件夹路径
            if (System.IO.Directory.Exists(savePath) == false)//判断文件夹是否存在
                System.IO.Directory.CreateDirectory(savePath);//创建文件夹
            savePath = Server.MapPath("~/Areas/CompletionMaterials/Upload/Temp/" + info.Fl_Item + "/" + info.Fl_FileType + "/脊背/" + fileName + "脊背.docx");
            using (DocX docx = DocX.Load(path))
            {
                docx.Bookmarks.ForEach(f =>
                {
                    string bookMarkName = f.Name;
                    if (info.ContainProperty(bookMarkName))
                    {
                        var obj = Reflection.GetProperty(info, bookMarkName);
                        var value = obj ?? "";
                        var propertyType = value.GetType().FullName;
                        if (propertyType == "System.DateTime")
                        {
                            f.SetText(Convert.ToDateTime(value).ToString("yyyy年MM月dd日"));
                        }
                        else
                            f.SetText(value.ToString());
                        if (bookMarkName == "Fl_Numb")
                        {
                            f.SetText(Convert.ToInt32(value).ToString("D3"));
                        }
                    }
                });
                docx.SaveAs(savePath);
            }
            return savePath;
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileName">设置下载文件名称</param>
        /// <param name="filePath">下载文件真实路径</param>
        private void DownloadFile(string fileName, string filePath, bool IsDel = false)
        {
            FileInfo fileInfo = new FileInfo(filePath);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.WriteFile(fileInfo.FullName);
            Response.Flush();
            if (IsDel)
                System.IO.File.Delete(filePath);//删除已下载文件
            Response.End();
        }
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="fileName">要压缩的所有文件（完全路径)</param>
        /// <param name="fileName">文件名称</param>
        /// <param name="name">压缩后文件路径</param>
        public void ZipFileMain(string[] filenames, string[] fileName, string name)
        {
            ZipOutputStream s = new ZipOutputStream(System.IO.File.Create(name));
            Crc32 crc = new Crc32();
            //压缩级别
            s.SetLevel(9); // 0 - store only to 9 - means best compression
            try
            {
                int m = 0;
                foreach (string file in filenames)
                {
                    //打开压缩文件
                    FileStream fs = System.IO.File.OpenRead(file);//文件地址
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    //建立压缩实体
                    ZipEntry entry = new ZipEntry(fileName[m].ToString());//原文件名
                    //时间
                    entry.DateTime = DateTime.Now;
                    //空间大小
                    entry.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                    m++;
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                s.Finish();
                s.Close();
            }
        }
        /// <summary>
        /// 获取案卷档号
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetFileCode(string code)
        {
            string title = code.Substring(0, code.IndexOf('/'));
            string numb = code.Substring(code.IndexOf('/'), 4);
            string number = numb.Substring(1, 1);
            if (number == "3")
                numb = numb.Substring(0, 2);
            return title + numb;
        }
        /// <summary>
        /// 判断档号是否存在
        /// </summary>
        /// <param name="code">档案号</param>
        /// <param name="numb">流水号</param>
        /// <param name="flID">案卷主键</param>
        /// <returns></returns>
        public int GetFileCodeCount(string code, int numb, string flID = "")
        {
            string sql = " Fl_Code='" + code + "' ";
            if (code.IndexOf(".") >= 0)
            {
                sql = " Fl_Code like '" + GetFileCode(code) + "%' ";
            }
            if (flID != "")
                sql += " and Fl_ID!='" + flID + "' ";
            return BcdFilelistUIRule.GetCountBySql(sql + " and Fl_Numb=" + numb);
        }
        /// <summary>
        /// 获取节点名
        /// </summary>
        /// <param name="pftId">项目材料类型主键 节点Id</param>
        /// <returns></returns>
        public string GetNodeName(string pftId, int type = 1)
        {
            BcdProfiletypeInfo info = BcdProfiletypeUIRule.GetEntityById(new Guid(pftId));
            string name = "";
            if (info.Pft_PID == null)
                name = info.Fd_Numb + " " + info.Pft_Section + info.Fd_Name;
            else
                name = info.Fd_Numb + " " + info.Fd_Name;
            if (type == 1)
            {
                int count = BcdProfiletypeUIRule.GetSonCountByPftID(pftId);
                if (info.Pft_PID != null && count == 0)
                {
                    //未归档文件（已归档）
                    int count1 = BcdVolumedirectoryUIRule.GetCountBySql(" Pft_ID='" + pftId + "' and Vd_State=2 ");
                    //未归档文件（已审核通过）
                    int count2 = BcdVolumedirectoryUIRule.GetCountBySql(" Pft_ID='" + pftId + "' and Vd_State!=0 ");
                    //未归档文件（所有状态）
                    int counta = BcdVolumedirectoryUIRule.GetCountBySql(" Pft_ID='" + pftId + "' ");
                    name = "(<span class='span1'>" + count1 + "</span>" + "/" + "<span class='span2'>" + count2 + "</span>" + "/" + "<span class='span3'>" + counta + "</span>" + ")" + name;
                }
            }
            else
            {
                int count1 = BcdVolumedirectoryUIRule.GetCountBySql(" (Pft_ID='" + pftId + "' or Pft_PIds like '%" + pftId + "%') and Vd_State=2  ");
                int count2 = BcdFilelistUIRule.GetCountBySql(" (Pft_ID='" + pftId + "' or Pft_PIds like '%" + pftId + "%') ");
                name = "(<span class='span1'>" + count1 + "</span>" + "/" + "<span class='span2'>" + count2 + "</span>" + ")" + name;
            }
            return name;
        }
        /// <summary>
        /// 根据文件Id获取文件审批状态
        /// </summary>
        /// <param name="id">文件Id</param>
        /// <returns>审批状态(0=未审核，1=审核通过,2=已归档)</returns>
        public int GetFileState(string id)
        {
            BcdVolumedirectoryInfo info = BcdVolumedirectoryUIRule.GetEntityById(new Guid(id));
            return info.Vd_State;
        }
        /// <summary>
        /// 获取附件路径
        /// </summary>
        /// <param name="vdid">文件资料Id</param>
        /// <param name="pftid">资料类型Id</param>
        /// <returns></returns>
        public string FilePath(string vdid, string pftid)
        {
            string path = "";
            //工程项目竣工资料材料类型表
            BcdProfiletypeInfo info = BcdProfiletypeUIRule.GetEntityById(new Guid(pftid));
            path = info.P_Name + "/" + info.Pft_Section;
            string ids = info.Pft_ID + (info.Pft_PIds == null ? "" : info.Pft_PIds.ToString().Replace("'", ""));
            foreach (string id in ids.Split(','))
            {
                BcdProfiletypeInfo sinfo = BcdProfiletypeUIRule.GetEntityById(new Guid(id));
                path += sinfo.Fd_Name + "/";
            }
            return path + vdid;
        }
        /// <summary>
        /// 获取附件个数
        /// </summary>
        /// <param name="path"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public int GetFilesCount(string path, int count)
        {
            if (!System.IO.Directory.Exists(path))
            {
                return 0;
            }
            //如果嵌套文件夹很多，可以开子线程去统计
            count += System.IO.Directory.GetFiles(path).Length;
            foreach (var folder in System.IO.Directory.GetDirectories(path))
            {
                GetFilesCount(folder, count);
            }
            return count;
        }

        public void DoTest()
        {
            var aa = "";
        }

        protected void CreateAssistId(object uiRule, int assisId, out int ret)
        {
            ret = assisId;

            var objRet = Reflection.InvokeMethodByName(uiRule, "IsExitAssistId", assisId);

            var isExit = Convert.ToBoolean(objRet);
            if (isExit)
            {
                var newAssisId = GenerateRandom();
                ret = newAssisId;
                CreateAssistId(uiRule, newAssisId, out ret);
            }
        }
        //产生随机数，尽量不重复
        public int GenerateRandom(int iMax = 2000000000, int iNum = 10)
        {
            var ret = 0;
            long lTick = DateTime.Now.Ticks;
            List<int> lstRet = new List<int>();
            for (int i = 0; i < iNum; i++)
            {
                Random ran = new Random((int)lTick * i);
                int iTmp = ran.Next(iMax);
                lstRet.Add(iTmp);
                lTick += (new Random((int)lTick).Next(978));
            }

            Random ranIndex = new Random();
            var indexof = ranIndex.Next(0, iNum - 1);

            ret = lstRet[indexof];
            return ret;
        }

        public void SetSectionValue(string sessionName, object sessionObj)
        {
            Session.Timeout = 600;//设置Session超时时间为600分钟
            Session[sessionName] = sessionObj;
        }

        public T GetSessionValue<T>(string sessionName)
        {
            var sessionObj = Session[sessionName];
            return (T)sessionObj;
        }
        /// <summary>
        /// 公共文件UIRule
        /// </summary>
        public CommonFileUIRule CommonFileUIRule
        {
            get { return EngineContext.Current.Resolve<CommonFileUIRule>(); }
        }
    }
}